import sys
import json

import requests

from RequestBasedHueObject import RequestBasedHueObject
from HueLamp import HueLamp

class HueBridge(RequestBasedHueObject):\

    # Class to represent a Hue bridge.
    # It inherits from RequestBasedHueObject for easy real-time manipulation,
    # It uses self.setattr_(..., virtual=True) to set attributes on the instance
    # without making a request to the underlying bridge.

    READ_ONLY_ATTRIBUTES = [
            'IP_ADDRESS',
            'KEY',
            'STATE_URL',
            'GET_URL',
            'PUT_URL',
            'lamps',
            'groups',
            'schedules',
    ]

    def __init__(self, ipaddr=None, key=None, timeout=None):
        if not all([ipaddr, key]):
            sys.stderr.write("Come now, you didn't really think you could "
                             "instantiate a HueBridge without an IP address "
                             "and/or an application key, did you?")
            exit(1)

        if timeout:
            self.setattr_('TIMEOUT', timeout, virtual=True)
        else:
            self.setattr_('TIMEOUT', 20.0, virtual=True)

        # Set a bunch of attributes (virtually).
        self.setattr_('IP_ADDRESS', ipaddr, virtual=True)
        self.setattr_('KEY', key, virtual=True)
        self.setattr_('GET_URL', 'http://%s/api/%s' %
                    (self.IP_ADDRESS, self.KEY), virtual=True )

        # this is a stub.
        self.setattr_('PUT_URL', '%s%s' %
                    (self.IP_ADDRESS, self.KEY), virtual=True )

        self.setattr_('lamps', [], virtual=True)
        self.setattr_('groups', [], virtual=True)
        self.setattr_('schedules', [], virtual=True)

        # Get this bridge's state. 
        self.updateState()

    def updateState(self):
        result = requests.get( self.GET_URL )

        # set attributes for this bridge
        for key, val in result.json['config'].iteritems():
            print key, val
            self.setattr_(key, val, virtual=True)

        # build this bridge's lamps
        
        for key in sorted(result.json['lights'].keys()):
            val = result.json['lights'][key]
            self.lamps.append( HueLamp(self, key, val) )

        # TODO: implement groups and schedules.
